package com.enthal.basicpers

import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.MenuItem
import android.widget.Toast
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat

// https://www.cnblogs.com/itchq/p/3888284.html
class SettingsFragment : PreferenceFragmentCompat()
{
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey)

        val noticecnf = this.findPreference(getString(R.string.notice_listen_key)) as SwitchPreferenceCompat?
        noticecnf?.isChecked = RuntimeStatus.notificationListenerEnable(requireContext())

        val batignore = this.findPreference(getString(R.string.ignore_battery_key)) as SwitchPreferenceCompat?
        batignore?.isChecked = RuntimeStatus.isIgnoringBatteryOptimizations(requireContext())
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        Log.d("SETS", "onConfigurationChanged")

        Toast.makeText(requireContext(), "onConfigurationChanged", Toast.LENGTH_SHORT).show()

        super.onConfigurationChanged(newConfig)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        Log.d("SETS", "onOptionsItemSelected")
        Toast.makeText(requireContext(), "onOptionsItemSelected", Toast.LENGTH_SHORT).show()

        return super.onOptionsItemSelected(item)
    }

    override fun onPreferenceTreeClick(preference: Preference?): Boolean {
        if(null == preference) return false

        when(preference.key) {
            getString(R.string.notice_listen_key) -> {
                val switchpref = preference as SwitchPreferenceCompat
                val isenable = RuntimeStatus.notificationListenerEnable(requireContext())
                if(!isenable)
                    RuntimeStatus.settingsNotice(requireContext())
                else
                    switchpref.isChecked = isenable
            }
            getString(R.string.ignore_battery_key) -> {
                val switchpref = preference as SwitchPreferenceCompat
                val isenable = RuntimeStatus.isIgnoringBatteryOptimizations(requireContext())
                if(!isenable)
                    RuntimeStatus.requestIgnoreBatteryOptimizations(requireContext())
                else
                    switchpref.isChecked = isenable
            }
            else -> return false
        }

        return super.onPreferenceTreeClick(preference)
    }
}